/**
 * pages模版快速生成脚本,执行命令 npm run tep `文件名`
 */

const fs = require('fs');

const dirName = process.argv[2];
const curDate = new Date().toLocaleString().split(' ')[0] + ' ' + new Date().toLocaleString().split(' ')[1];

if (!dirName) {
    console.log('文件夹名称不能为空！');
    console.log('示例：yarn tep test');
    process.exit(0);
}

// 页面模版
const indexTep = `// createTime: ${curDate}';
import React, { useEffect } from 'react'
import { connect } from 'dva';
import styles from './index.less'

const ${titleCase(dirName)} = () => {
    useEffect(() => {}, []);
    return (
        <div className={styles.${dirName}Page}>
            ${dirName}
        </div>
    );
}

export default connect(({ ${dirName}, loading }: any) => ({
    ${dirName},
    loading
}))(${titleCase(dirName)});
`;

// less文件模版
const lessTep = `// createTime: ${curDate}`;

// model文件模版
const modelTep = `// createTime: ${curDate};
import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { demo } from './service';

export interface StateType {
    demoData: any;
}

export type Effect = (
    action: AnyAction,
    effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T }
) => void;

export interface ModelType {
    namespace: string;
    state: StateType;
    effects: {
        demo: Effect;
    };
    reducers: {
        save: Reducer<StateType>;
    };
}

export const initState = {
    demoData: []
};

const Model: ModelType = {
    namespace: '${dirName}',
    state: {
        ...initState
    },

    reducers: {
        save(state, { payload }) {
            return {
                ...state,
                ...payload
            };
        }
    },

    effects: {
        *demo({ payload }, { call, put }) {
            const { status, data } = yield call(demo, { ...payload });
            if (status === 'ok') {
                yield put({
                    type: 'save',
                    payload: {
                        topData: data
                    }
                });
            }
        }
    }
};
export default Model;
`;

// service页面模版
const serviceTep = `// createTime: ${curDate}
import request from '@/utils/request';

interface ParamsType {
    [key: string]: any;
}

export function demo(data: ParamsType) {
    return request('/mock/api/demo', {
        method: 'POST',
        data
    });
}
`;

fs.mkdirSync(`./src/pages/${dirName}`); // mkdir $1
process.chdir(`./src/pages/${dirName}`); // cd $1

fs.writeFileSync('index.tsx', indexTep);
fs.writeFileSync('index.less', lessTep);
fs.writeFileSync('model.ts', modelTep);
fs.writeFileSync('service.ts', serviceTep);

// eslint-disable-next-line no-console
console.log(`模版${dirName}已创建`);

function titleCase(str) {
    const array = str.toLowerCase().split(' ');
    for (let i = 0; i < array.length; i++) {
        array[i] = array[i][0].toUpperCase() + array[i].substring(1, array[i].length);
    }
    const string = array.join(' ');
    return string;
}

process.exit(0);
